package com.example.wwk.graduationpractice.SmackUtils;

import android.content.Intent;
import android.util.Log;

import com.example.wwk.graduationpractice.Broadcast.MessageComeBroadReceiver;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;

import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;

/**
 * Created by wwk on 2017/4/12.
 * 消息监听
 */

public class ChatListenerUtils {
    public static final int MsgCome = 100;
    private static String TAG = "123";
    public static class ChatListener implements ChatManagerListener {
        @Override
        public void chatCreated(Chat chat, boolean b) {
            chat.addMessageListener(new ChatMessageListener() {
                @Override
                public void processMessage(Chat chat, Message message) {
                    try {//当chat连接，由于openfire服务器会发送多条body为null的消息，所以异常捕获
                        String from = message.getFrom().toString();   //jid
                        from = from.substring(0, from.indexOf("@"));
                        String body = message.getBody().toString();
                        Log.d(TAG, "chatUtils " + from);
                        if (!body.equals("")) {//当消息内容不为空，且不是当前正在通话的用户
                            Log.d(TAG, "chatUtils " + body);
                            Intent intent  =  new Intent(MessageComeBroadReceiver.MSG_COME);
                            intent.putExtra("from",from);
                            intent.putExtra("body",body);
                            MyApplication.getContext().sendBroadcast(intent);
                        }
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }


                }
            });
        }
    }
}
